/**
 * Copyright 2011, Under-Ground Studio.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.zju.vlis.aus.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.edu.zju.vlis.aus.R;
import cn.edu.zju.vlis.aus.bean.UsageRecord;
import cn.edu.zju.vlis.aus.db.UsageRecordDAO;
import cn.edu.zju.vlis.aus.util.IconCache;
import cn.edu.zju.vlis.aus.util.IconCache.LoadSingleIconTask;

public class SettingAppFilterActivity extends Activity implements
		OnClickListener {
	private Button btnOk, btnCancel;
	private TextView title;
	
	private int selectedCount;

	private ArrayList<UsageRecord> allUsageRecord = null;
	private UsageRecordDAO dao;
	private SettingStatisticsAppListAdapter listAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dao = new UsageRecordDAO(this);
		setContentView(R.layout.setting_statistic_app_list);
		//sub views
		btnOk = (Button) findViewById(R.id.button_ok);
		btnCancel = (Button) findViewById(R.id.button_cancel);
		btnOk.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		title = (TextView) findViewById(R.id.title);
		title.setText(R.string.title_setting_statistic_app);

		ListView listView = (ListView) findViewById(R.id.list_setting_statistic_app);
		// set empty view
		LayoutInflater inflater = LayoutInflater.from(this);
		View emptyView = inflater.inflate(R.layout.list_empty_view_app_filter, null);
		emptyView.setVisibility(View.GONE);
		((ViewGroup) listView.getParent()).addView(emptyView);
		listView.setEmptyView(emptyView);
		// get the app list from the db
		allUsageRecord = dao.getAllStatisticByAppName();
		listAdapter = new SettingStatisticsAppListAdapter();
		listView.setAdapter(listAdapter);
		//set title with count
		selectedCount = 0;
		for(UsageRecord r:allUsageRecord){
			if(r.isStatistic()){
				selectedCount++;
			}
		}
		setTitleWithCount(selectedCount, allUsageRecord.size());

		// set OnItemClickListener
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				listAdapter.toggle(position, view);
				if(((StatisticsAppListItemView)view).isChecked()){
					selectedCount++;
				}else{
					selectedCount--;
				}
				setTitleWithCount(selectedCount, allUsageRecord.size());
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_ok:
			ArrayList<UsageRecord> changedUsageRecord = (ArrayList<UsageRecord>) listAdapter
					.getChangedList();
			if (changedUsageRecord.size() > 0) {
				dao.updateStatistic(changedUsageRecord);
			}
			setResult(RESULT_OK);
			finish();
			break;
		case R.id.button_cancel:
			setResult(RESULT_CANCELED);
			finish();
			break;
		}
	}

	@Override
	protected void onDestroy() {
		dao.close();
		super.onDestroy();
	}
	
	private void setTitleWithCount(int selected,int total){
		String filterTitle = getResources().getString(R.string.title_setting_statistic_app);
		StringBuffer titleBuilder = new StringBuffer(filterTitle);
		titleBuilder = titleBuilder.append('(').append(selected).append('/').append(total).append(')');
		title.setText(titleBuilder);
	}

	private class SettingStatisticsAppListAdapter extends BaseAdapter {
		private boolean[] changed;

		public SettingStatisticsAppListAdapter() {
			super();
			/*
			 * initiate the changed array which is for recording checked state
			 * changing.
			 */
			int size = getCount();
			changed = new boolean[size];
			for (int i = 0; i < size; i++) {
				changed[i] = false;
			}
		}

		@Override
		public int getCount() {
			if (allUsageRecord != null) {
				return allUsageRecord.size();
			} else {
				return 0;
			}
		}

		@Override
		public Object getItem(int position) {
			if (allUsageRecord != null) {
				return allUsageRecord.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			StatisticsAppListItemView v;
			if (convertView == null) {
				v = new StatisticsAppListItemView(SettingAppFilterActivity.this);
			} else {
				v = (StatisticsAppListItemView) convertView;
			}
			UsageRecord rec = (UsageRecord) getItem(position);
			if (rec != null) {
				// set app name
				v.setTextAppName(rec.getAppName());
				// set icon
				Drawable icon = IconCache.getIcon(rec.getPackageName());
				if (icon == null) {
					icon = IconCache.getDefaultIcon();
					new LoadSingleIconTask(SettingAppFilterActivity.this,
							rec.getPackageName(),
							((StatisticsAppListItemView) v).getImageAppIcon())
							.execute();
				}
				v.setImageAppIcon(icon);
				v.setChecked(rec.isStatistic());
			}
			return v;
		}

		public void toggle(int position, View itemView) {
			changed[position] = !changed[position];
			UsageRecord rec = (UsageRecord)getItem(position);
			rec.setStatistic(!rec.isStatistic());
			((StatisticsAppListItemView) itemView).toggle();
		}

		public List<UsageRecord> getChangedList() {
			ArrayList<UsageRecord> changedUsageRecord = new ArrayList<UsageRecord>();
			for (int i = 0; i < changed.length; i++) {
				if (changed[i] == true) {
					UsageRecord item = allUsageRecord.get(i);
					changedUsageRecord.add(item);
				}
			}
			return changedUsageRecord;
		}

	}

	private class StatisticsAppListItemView extends LinearLayout {
		private TextView textAppName;
		private ImageView imageAppIcon;
		private CheckBox checkBox;

		public StatisticsAppListItemView(Context context) {
			super(context);
			LayoutInflater inflater = LayoutInflater.from(context);
			View root = inflater.inflate(
					R.layout.list_item_setting_statistic_app, this);
			textAppName = (TextView) root
					.findViewById(R.id.text_statistics_app_name);
			imageAppIcon = (ImageView) root
					.findViewById(R.id.image_statistics_app_icon);
			checkBox = (CheckBox) root.findViewById(R.id.check_box);
		}

		public ImageView getImageAppIcon() {
			return imageAppIcon;
		}

		public void setTextAppName(String appName) {
			this.textAppName.setText(appName);
		}

		public void setImageAppIcon(Drawable drawable) {
			this.imageAppIcon.setImageDrawable(drawable);
		}

		/**
		 * Change the checked state of the check box
		 * 
		 * @param checked
		 *            The new checked state
		 */
		public void setChecked(boolean checked) {
			checkBox.setChecked(checked);
		}
		
		public boolean isChecked(){
			return checkBox.isChecked();
		}

		/**
		 * Change the checked state of the view to the inverse of its current
		 * state
		 * 
		 */
		public void toggle() {
			checkBox.toggle();
		}
	}
}
